//index.js
//获取应用实例
const app = getApp()

Page({
  data: {
    page: 0,
    index: 0,
    translated: false,
    words: [],
    content: 'Hello World',
    mode: '随机',
    url: "get",
    now: '顺序',
  },
  onLoad: function () {
    this.requestMore(this.data.page);
  },

  translate: function(e) {
    if (this.data.translated) {
      this.setData({
        content: this.data.words[this.data.index]['en'],
        translated: false
      })
    } else {
      this.setData({
        content: this.data.words[this.data.index]['cn'],
        translated: true
      })
    }
  },

  nextWord: function(e) {
    var index = this.data.index + 1;
    if (this.data.words.length < 10) {
      wx.showToast({
        title: '没有更多词le',
      })
      this.setData({
        page: 0,
        index: 0,
      })
      this.requestMore(this.data.page);
    } else {
      if (index == 10) {
        this.requestMore(this.data.page);
      } else {
        this.setData({
          index: index
        })
      }
      this.newWord();
    }
    
  },

  requestMore: function(page) {
    var that = this;
    wx.request({
      url: 'http://api.kernelylz.cn:8888/' + that.data.url,
      data: {
        page: page,
        limit: 10
      },
      success: function(res) {
        if (that.data.url == "get") {
          page += 1;
        }
        that.setData({
          page: page,
          words: res.data,
          index: 0,
        })
        that.newWord();
      }
    })
  },

  newWord: function(e) {
    this.setData({
      content: this.data.words[this.data.index]['en']
    });
  },

  changeMode: function(e) {
    if (this.data.now == "顺序") {
      this.setData({
        mode: '顺序',
        url: "random",
        page: 0,
        now: '随机'
      })
    } else {
      this.setData({
        mode: '随机',
        url: "get",
        now: '顺序'
      })
    }
    
    this.requestMore(this.data.page);
  }
})
